#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>

#define MULTICAST_GROUP "224.0.0.1"
#define PORT 5556

int main() {
    int sockfd;
    struct sockaddr_in local_addr, group_addr;
    struct ip_mreq mreq;
    char buffer[1024];
    socklen_t addrlen = sizeof(group_addr);

    // 创建 UDP 套接字
    if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
        perror("socket creation failed");
        exit(EXIT_FAILURE);
    }

    // 设置本地地址
    memset(&local_addr, 0, sizeof(local_addr));
    local_addr.sin_family = AF_INET;
    local_addr.sin_addr.s_addr = INADDR_ANY;
    local_addr.sin_port = htons(PORT);

    // 绑定本地地址
    if (bind(sockfd, (struct sockaddr *)&local_addr, sizeof(local_addr)) < 0) {
        perror("bind failed");
        exit(EXIT_FAILURE);
    }

    // 加入组播组
    mreq.imr_multiaddr.s_addr = inet_addr(MULTICAST_GROUP);
    mreq.imr_interface.s_addr = INADDR_ANY;
    if (setsockopt(sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) < 0) {
        perror("setsockopt (IP_ADD_MEMBERSHIP) failed");
        exit(EXIT_FAILURE);
    }

    while (1) {
        // 接收服务信息
        memset(buffer, 0, sizeof(buffer));
        if (recvfrom(sockfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&group_addr, &addrlen) < 0) {
            perror("recvfrom failed");
        }
        printf("Discovered service: %s\n", buffer);
    }

    // 关闭套接字
    close(sockfd);
    return 0;
}